package no18.javaio;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 读取随机访问文件
 * RandomAccessFile 与 DataInputStream  DataOutputStream比较来看
 * DataInputStream  DataOutputStream是按顺序读写文件,并且输入输出要分别创建流
 * RandomAccessFile可以随机在任意位置读写文件,并且输入输出流为同一个流
 * 
 * @author gao
 *
 */
public class UsingRandomAccessFile {
	private final static String FILE_NAME = "D:/work/project/complex/complex.thinkinjava/src/main/java/no18/javaio/random.txt";
	
	static void display() throws IOException{
		//r表示只读
		RandomAccessFile rf = new RandomAccessFile(FILE_NAME,"r");
		//前面七行以Double读取
		for(int i=0;i<7;i++){
			System.out.println("Value "+i+":" +rf.readDouble());
		}
		//以UTF读取
		System.out.println(rf.readUTF());
		rf.close();
	}
	
	public static void main(String[] args) throws IOException{
		//读写方式
		RandomAccessFile rf = new RandomAccessFile(FILE_NAME,"rw");
		//写入七行Double数据
		for (int i = 0; i < 7; i++) {
			rf.writeDouble(i*1.414);
		}
		//写入一行UTF数据
		rf.writeUTF("The end of the file");
		rf.close();
		display();//显示一下
		
		rf = new RandomAccessFile(FILE_NAME,"rw");
		rf.seek(5*8);//到第40指针偏量
		rf.writeDouble(47.0001);
		rf.close();
		display();
	}
}
